/**
 * Created by xiewl on 2016/5/10.
 */
var urlParamObj = $$.util.urlParamToObj();
//计算form-box的高度
var calcFormHeight = function () {
    var clientHeight = document.body.clientHeight;
    var formEle = $('.form-box').get(0);
    var headerHeight = formEle.offsetTop + formEle.offsetParent.offsetTop;
    $('.form-box').css('height',clientHeight - headerHeight - 5);
};
//节点弹框相关====
var nodeModalOperate=function(){
    //日期控件函数===============================
    var timepicker=function () {
        $('#reDate').datetimepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayBtn: true,
            minView:2,
            pickerPosition:"bottom-right"
        });
        $('#startDate').datetimepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayBtn: true,
            minView:2,
            pickerPosition:"bottom-right"
        });
        $('#endDate').datetimepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayBtn: true,
            minView:2,
            pickerPosition:"bottom-right"
        });
    };
    timepicker();
    //绝对与相对日期的切换==============================
    $('#selectdate').on('change', function () {
        if($(this).val()=='绝对日期'){
           $('#specialBd').css('display','none')
        }else{
            $('#specialBd').css('display','block')
        }
    });
//tr点击事件
    $('tbody').on('click','tr',function(e){
        $(this).find('.radio_check').click()
    });
    $('tbody').on('click','.radio_check',function(e){
        e.stopPropagation();
    })
};
//节点操作
var nodeOperate = function () {
    var isclick=false;//用于判断是否选择创建模板==
    var isEdit=false;//用于判断页面是否为编辑还是新建
    var editIndex='';//用于判断编辑传入的节点号
    $('#nextEdit').click(function(){
        isclick=true;
        isEdit=false;
        singleClear();
        repeatClear();
        timeClear();
        referenceNode();//参考节点的插入
        if($('#optionsRadios1').prop('checked')){
            $('#editPointone').modal('hide');
            $('#editPointtwo').modal('show');
        }else if($('#optionsRadios2').prop('checked')){
            $('#editPointone').modal('hide');
            $('#editPointthr').modal('show');
        }else{
            $('#editPointone').modal('hide');
            $('#timeNode').modal('show');
        }

    });
    //新增节点
    $('.operate-box .main-btn,.operate-cover').click(function () {
        $('.operate-box').toggleClass('active');
        $('.operate-cover').toggle();
    });
    $('.operate-box').on('click','.a1',function () {
        $('#editPointone').modal('show');
        $('.operate-box').toggleClass('active');
        $('.operate-cover').toggle();
    });
    //删除节点
    $('.form-node').on('click','.del-btn',function () {
        var $thisParent = $(this).parents('.node-item-box');
        var deleteData=JSON.parse(decodeURI($thisParent.attr('data-message')));
        var baseStep=deleteData.title;
        console.log(deleteData);
        if(deleteData.periodtype==0){
            $$.modal.confirm('您删除的是绝对节点，删除后相关参考节点也将被删除，您确认要删除么？','取消','确认',function(){
                $thisParent.remove();
                var $nodeBox=$('.node-item-box');
                for(var i= 0,len=$nodeBox.length;i<len;i++){
                    var nodeBaseStep=JSON.parse(decodeURI($nodeBox.eq(i).attr('data-message'))).basestep;
                    if(nodeBaseStep==baseStep){
                        $nodeBox.eq(i).remove()
                    }
                }
                nodeInit();//初始化节点
            })
        }else{
            $$.modal.confirm('确认删除吗？','取消','确认',function(){
                $thisParent.remove();
                nodeInit();//初始化节点顺序
            });
        }
    });
    //复制节点
    $('.operate-box').on('click','.a2',function () {
        $('#editPointfour').find('tbody').html('');
        var copyNode=function(num,name,type,formSum,isClose){
            var html=document.createElement('tr');
            html.innerHTML="<tr>"+
            "<td>"+num+"</td>"+
            "<td>"+name+"</td>"+
            "<td>"+type+"</td>"+
            "<td>"+formSum+"</td>"+
            "<td>"+isClose+"</td>"+
            "<td>"+
            "<div class='radio radio-primary'>"+
            "<label>"+
            "<input type='radio' name='option'  value='ischeck' class='radio_check'>"+
            "<span class='circle'></span>"+
            "<span class='check'></span>"+
            "</label>" +
            " </div> " +
            "</td> " +
            "</tr>";
            $('#editPointfour').find('tbody').append(html)
        };
        var $copyTr=$('.form-node .node-item-box');
        var len=$copyTr.length;
        if(!len){
            $$.modal.tips('请先创建一个节点',1500);
            return false;
        }
        var nodeType='';//定义表类型
        var formSum='';//定义其中表的数量
        var isClose='';//定义节点是否关闭
        for(var i= 0;i<len;i++){
            var nodeData=JSON.parse(decodeURI($copyTr.eq(i).attr('data-message')));
            if(nodeData.isInfinite==1){
                nodeType='重复性节点'
            }else{
                if(nodeData.periodtype==0){
                    nodeType='一次性节点（参考节点）'
                }else{
                    nodeType='一次性节点'
                }
            }
            if(nodeData.labled==0){
                isClose='关闭'
            }else if(nodeData.labled==1){
                isClose='开启'
            }
            formSum=nodeData.forms.length;
            copyNode(i,nodeData.title,nodeType,formSum,isClose)
        }
        $('#editPointfour').modal('show');
        $('.operate-box').toggleClass('active');
        $('.operate-cover').toggle();
    });
    //复制节点渲染到页面上========
    $('#editPointfour .copy-node').click(function(){
        var selectIndex = $('#editPointfour tbody .radio_check:checked').parents('tr').index();
        if(selectIndex < 0){
            $$.modal.alert('请选择节点','确定')
        }else{
            var cloneNode=$('.form-node .node-item-box').eq(selectIndex).clone();
            cloneNode.find('.name').text(cloneNode.find('.name').text()+'+copy+'+copyRandom());
            var cloneData=JSON.parse(decodeURI(cloneNode.attr('data-message')));
            cloneData.title=cloneNode.find('.name').text();
            cloneData.id && (cloneData.copystepid = cloneData.id);
            cloneData.id='';
            var cloneReplace=encodeURI(JSON.stringify(cloneData));
            cloneNode.attr('data-message',cloneReplace);
            //如果是绝对节点就添加到box最下面，不是就复制到相应的参考节点下去；
            if(cloneData.periodtype==0){
                $('.form-node').append(cloneNode)
            }else{
                if(cloneData.basestep=='开始随访'){
                    $('.begin-node').append(cloneNode);
                }else{
                    var cloneBasestep=cloneData.basestep;
                    var boxAll=$('.node-item-box');
                    var cloneArry=[];
                    for(var i= 0,len=boxAll.length;i<len;i++){
                        var cloneData=JSON.parse(decodeURI(boxAll.eq(i).attr('data-message'))).basestep;
                        if(cloneData==cloneBasestep){
                            cloneArry.push(boxAll.eq(i))
                        }
                    }
                    cloneArry[cloneArry.length-1].after(cloneNode);
                }
            }
            $('#editPointfour').modal('hide');
            nodeInit();
        }
    });

    //填写描述点击========
    $('.form-node').on('click','.gray',function(){
            $(this).parents().eq(1).find('.edit-btn').click();
    });
    //删除表单
    $('.form-node').on('click','.node-list .blue .del-form',function(e){
        var json = JSON.parse(decodeURI($(this).parents('.node-item-box').attr('data-message')));
        var formIndex= $(this).parents('.node-form-item').index() - 1;
        json.forms.splice(formIndex,1);
        $(this).parents('.node-item-box').attr('data-message',encodeURI(JSON.stringify(json)));
        $(this).parents('.node-form-item').remove();
        e.stopPropagation();
    });
    //编辑节点基本信息
    $('.form-node').on('click','.edit-btn',function(){
        isEdit=true;
        var $this=$(this).parents('.node-item-box');
        editIndex=$('.form-node .node-item-box').index($this);
        var dataJson=JSON.parse(decodeURI($this.attr('data-message')));
        referenceNode();//参考节点的插入
        if(dataJson.isInfinite==0&&dataJson.periodtype!=0){//一次节点编辑
            singleClear();
            var $thisparent=$('#editPointtwo');
            $thisparent.find('.node-name').val(dataJson.title);
            $thisparent.find('.date-num').val(dataJson.period);
            $thisparent.find('.selectReference').val(dataJson.basestep)
            if(dataJson.periodtype==5){
                $thisparent.find('.date-num-type').val('月')
            }else if(dataJson.periodtype==4){
                $thisparent.find('.date-num-type').val('周')
            }else if(dataJson.periodtype==3){
                $thisparent.find('.date-num-type').val('日')
            }
            if(dataJson.description=='单击填写描述'){
                dataJson.description=''
            }
            $thisparent.find('.node-des').val(dataJson.description);
            if(dataJson.filltype==3){
                $thisparent.find('.check-limit').val('v1')
            }else{
                $thisparent.find('.check-limit').val('v2')
            }
            if(dataJson.labled==1){
                $thisparent.find('.comment-enable').click();
            }
            $thisparent.find('.before-value').val(dataJson.beforenotify.time);
            if(dataJson.beforenotify.direct==3){
                $thisparent.find('.before-doc').click();
                $thisparent.find('.before-patient').click();
            }else if(dataJson.beforenotify.direct==1){
                $thisparent.find('.before-doc').click();
            }else if(dataJson.beforenotify.direct==2){
                $thisparent.find('.before-patient').click();
            }
            if(dataJson.notify){
                if(dataJson.notify.direct==3){
                    $thisparent.find('.notify-doc').click();
                    $thisparent.find('.notify-patient').click();
                }else if(dataJson.notify.direct==1){
                    $thisparent.find('.notify-doc').click();
                }else if(dataJson.notify.direct==2){
                    $thisparent.find('.notify-patient').click();
                }
            }
            $thisparent.find('.over-sum').val(dataJson.overduenotify.time);
            if(dataJson.overduenotify.direct==3){
                $thisparent.find('.over-doc').click();
                $thisparent.find('.over-patient').click();
            }else if(dataJson.overduenotify.direct==1){
                $thisparent.find('.over-doc').click();
            }else if(dataJson.overduenotify.direct==2){
                $thisparent.find('.over-patient').click();
            }
            if(dataJson.msgtype==3){
                $thisparent.find('.msg-system').click();
                $thisparent.find('.msg-message').click();
            }else if(dataJson.msgtype==1){
                $thisparent.find('.msg-system').click();
            }else if(dataJson.msgtype==2){
                $thisparent.find('.msg-message').click();
            }
            $thisparent.modal('show');
        }else if(dataJson.isInfinite==1){//重复节点编辑
            repeatClear();
            var $thrparent=$('#editPointthr');
            $thrparent.find('.selectReference').val(dataJson.basestep);
            $thrparent.find('.continued-num').val(dataJson.goingtime);
            if(dataJson.periodtype==5){
                $thrparent.find('.repeat-mode').val('每月重复')
            }else if(dataJson.periodtype==4){
                $thrparent.find('.repeat-mode').val('每周重复')
            }else if(dataJson.periodtype==3){
                $thrparent.find('.repeat-mode').val('每日重复')
            }
            if(dataJson.goingtype==5){
                $thrparent.find('.continued-num-type').val('月')
            }else if(dataJson.goingtype==4){
                $thrparent.find('.continued-num-type').val('周')
            }else if(dataJson.goingtype==3){
                $thrparent.find('.continued-num-type').val('日')
            }
            $thrparent.find('.node-name').val(dataJson.title);
            if(dataJson.description=='单击填写描述'){
                dataJson.description=''
            }
            $thrparent.find('.node-des').val(dataJson.description);
            if(dataJson.filltype==1){
                $thrparent.find('.node-jurisdiction').val('v2')
            }else if(dataJson.filltype==3){
                $thrparent.find('.node-jurisdiction').val('v1')
            }
            if(dataJson.labled==1){
                $thrparent.find('.node-review').click()
            }
            $thrparent.find('.before-value').val(dataJson.beforenotify.time);
            if(dataJson.beforenotify.direct==3){
                $thrparent.find('.before-doc').click();
                $thrparent.find('.before-patient').click();
            }else if(dataJson.beforenotify.direct==1){
                $thrparent.find('.before-doc').click();
            }else if(dataJson.beforenotify.direct==2){
                $thrparent.find('.before-patient').click();
            }
            if(dataJson.notify.direct==3){
                $thrparent.find('.notify-doc').click();
                $thrparent.find('.notify-patient').click();
            }else if(dataJson.notify.direct==1){
                $thrparent.find('.notify-doc').click();
            }else if(dataJson.notify.direct==2){
                $thrparent.find('.notify-patient').click();
            }
            $thrparent.find('.over-value').val(dataJson.overduenotify.time);
            if(dataJson.overduenotify.direct==3){
                $thrparent.find('.over-doc').click();
                $thrparent.find('.over-patient').click();
            }else if(dataJson.overduenotify.direct==1){
                $thrparent.find('.over-doc').click();
            }else if(dataJson.overduenotify.direct==2){
                $thrparent.find('.over-patient').click();
            }
            if(dataJson.msgtype==3){
                $thrparent.find('.msg-system').click();
                $thrparent.find('.msg-message').click();
            }else if(dataJson.msgtype==1){
                $thrparent.find('.msg-system').click();
            }else if(dataJson.msgtype==2){
                $thrparent.find('.msg-message').click();
            }
            $thrparent.modal('show');
        }else if(dataJson.isInfinite==0&&dataJson.periodtype==0){//编辑时间节点
            timeClear();//时间节点内容清空
            var $thisparent=$('#timeNode');
            console.log(dataJson);
            $thisparent.find('.node-name').val(dataJson.title);
            if(dataJson.description=='单击填写描述'){
                dataJson.description=''
            }
            $thisparent.find('.node-des').val(dataJson.description);
            var fillType='';//定义权限
            if(dataJson.filltype==3){
                fillType='v1'
            }else{
                fillType='v2'
            }
            $thisparent.find('.node-jurisdiction').val(fillType);
            if(dataJson.labled==1){
                $thisparent.find('.comment-enable').click();
            }
            if(dataJson.beforenotify.direct==3){
                $thisparent.find('.before-doc').click();
                $thisparent.find('.before-patient').click()
            }else if(dataJson.beforenotify.direct==1){
                $thisparent.find('.before-doc').click();
            }else if(dataJson.beforenotify.direct==2){
                $thisparent.find('.before-patient').click()
            }
            $thisparent.find('.before-value').val(dataJson.beforenotify.time);
            if(dataJson.notify.direct==3){
                $thisparent.find('.notify-doc').click();
                $thisparent.find('.notify-patient').click();
            }else if(dataJson.notify.direct==1){
                $thisparent.find('.notify-doc').click();
            }else if(dataJson.notify.direct==2){
                $thisparent.find('.notify-patient').click();
            }
            if(dataJson.overduenotify.direct==3){
                $thisparent.find('.over-doc').click();
                $thisparent.find('.over-patient').click();
            }else if(dataJson.overduenotify.direct==1){
                $thisparent.find('.over-doc').click();
            }else if(dataJson.overduenotify.direct==2){
                $thisparent.find('.over-patient').click();
            }
            $thisparent.find('.over-value').val(dataJson.overduenotify.time);
            if(dataJson.msgtype==3){
                $thisparent.find('.msg-system').click();
                $thisparent.find('.msg-message').click();
            }else if(dataJson.msgtype==1){
                $thisparent.find('.msg-system').click();
            }else if(dataJson.msgtype==2){
                $thisparent.find('.msg-message').click();
            }
            $thisparent.modal('show');
        }
    });
    //保存节点开始================================================================
    var saveItem=[];
    //保存一次性节点
    $('#saveOnceNodeBtn').click(function () {
        var $currentParent = $('#editPointtwo');
        var nodeName = $.trim($currentParent.find('.node-name').val());//节点名称
        var dateNum = $.trim($currentParent.find('.date-num').val());//距离上个节点
        var dateNumType = $currentParent.find('.date-num-type :selected').val();
        var datePeriodtype='';//定义一次性节点的月，周，日
        var fuhao='+';
        if(dateNumType=='月'){
            datePeriodtype=5
        }else if(dateNumType=='周'){
            datePeriodtype=4
        }else if(dateNumType=='日'){
            datePeriodtype=3
        }
        var beforeValue= $.trim($currentParent.find('.before-value').val());
        var beforeNotify='';//定义提前提醒
        if($currentParent.find('.before-doc').prop('checked')&&$currentParent.find('.before-patient').prop('checked')){
            beforeNotify=3;
        }else if($currentParent.find('.before-doc').prop('checked')){
            beforeNotify=1;
        }else if($currentParent.find('.before-patient').prop('checked')){
            beforeNotify=2;
        }
        var notifyNew='';//定义到时提醒
        if($currentParent.find('.notify-doc').prop('checked')&&$currentParent.find('.notify-patient').prop('checked')){
            notifyNew=3;
        }else if($currentParent.find('.notify-doc').prop('checked')){
            notifyNew=1;
        }else if($currentParent.find('.notify-patient').prop('checked')){
            notifyNew=2;
        }
        var overNotify='';//定义预期提醒
        var overVlue= $.trim($currentParent.find('.over-sum').val());
        if($currentParent.find('.over-doc').prop('checked')&&$currentParent.find('.over-patient').prop('checked')){
            overNotify=3;
        }else if($currentParent.find('.over-doc').prop('checked')){
            overNotify=1;
        }else if($currentParent.find('.over-patient').prop('checked')){
            overNotify=2;
        }
        var msgType='';//系统或者短信提醒
        if($currentParent.find('.msg-system').prop('checked')&&$currentParent.find('.msg-message').prop('checked')){
            msgType=3;
        }else if($('.msg-system').prop('checked')){
            msgType=1;
        }else if($('.msg-message').prop('checked')){
            msgType=2;
        }
        var checkLimit = $currentParent.find('.check-limit :selected').val();//定义权限===
        var jurisdictionLimit='';
        if(checkLimit=='v1'){
            jurisdictionLimit=3;
        }else if(checkLimit=='v2'){
            jurisdictionLimit=1;
        }
        var commentEnable='';//定义节点评论的开启
        if($currentParent.find('.comment-enable').prop('checked')){
            commentEnable=1
        }else{
            commentEnable=0;
        }
        var nodeDes = $.trim($currentParent.find('.node-des').val());
        if(nodeDes==''){
            nodeDes='单击填写描述'
        }
        var stepIndex='';
        //if($('.form-node').html()==''){
        //    stepIndex=0;
        //}else{
        //    stepIndex=JSON.parse(decodeURI($('.form-node .node-item-box:last-child').attr('data-message'))).step+1;
        //}
        var singleReference=$currentParent.find('.selectReference').val();//定义参考节点
        saveItem={//参数
            periodtype:datePeriodtype,
            period:dateNum,
            isInfinite:0,
            templateid:urlParamObj.templateid,
            title:nodeName,
            beforenotify:{ type:3,time:beforeValue,direct:beforeNotify},
            notify:{direct:notifyNew},
            overduenotify:{type:3,time:overVlue,direct:overNotify},
            filltype:jurisdictionLimit,
            description:nodeDes,
            step:stepIndex,
            forms:[],
            msgtype:msgType,
            labled:commentEnable,
            basestep:singleReference
        };
        var boxNode=$('.node-item-box');//找到所有的节点
        var isNode=false;//定义是否有字节点
        var changeNode=false;//定义改变后的参考节点是否有子节点
        var isRepeat=false;//定义名字是否重复
        var len=boxNode.length;
        if(isEdit==false){//判断为新建一次性节点
            if(nodeName!=''){
                if(dateNum==''){
                    $$.modal.alert('距上一个节点不能为空','确定')
                }else{
                    for(var i=0;i<len;i++){//判断节点名称是不是重复
                        if(nodeName==boxNode.eq(i).find('.name').text()){
                            isRepeat=true
                        }
                    }
                    if(isRepeat==true){//判断节点名称重复
                        $$.modal.alert('节点名称重复，请修改','确定');
                        isRepeat=false;
                    }else{
                        var singleNode=new pageRendering(nodeName,fuhao,dateNum,dateNumType,nodeDes,saveItem.forms);
                        var html=singleNode.html;
                        var saveItemStr=JSON.stringify(saveItem);
                        html.setAttribute('data-message',encodeURI(saveItemStr));
                        if(singleReference=='开始随访'){
                            $('.begin-node').append(html)
                        }else{
                            for(var i= 0;i<len;i++){//判断参考节点是否有子节点
                                var boxNodeJson=JSON.parse(decodeURI(boxNode.eq(i).attr('data-message')));
                                if(boxNodeJson.basestep==singleReference){
                                    isNode=true;
                                    break;
                                }
                            }
                            if(isNode==false){//当参考节点没有子节点时
                                for(var i= 0;i<len;i++){
                                    var boxNodeData=JSON.parse(decodeURI(boxNode.eq(i).attr('data-message')));
                                    if(boxNodeData.title==singleReference){
                                        boxNode.eq(i).after(html);
                                    }
                                }
                            }else{//当参考节点有子节点时
                                var nodeArry=[];
                                for(var i= 0;i<len;i++){
                                    var boxNodeData=JSON.parse(decodeURI(boxNode.eq(i).attr('data-message')));
                                    if (boxNodeData.basestep==singleReference){
                                        nodeArry.push(boxNode.eq(i))
                                    }
                                }
                                nodeArry[nodeArry.length-1].after(html);
                            }
                        }
                        $('#editPointtwo').modal('hide');
                        nodeInit();
                        singleClear();
                    }
                }
            }else{
                $$.modal.alert('节点名称不能为空','确定');
            }
        }else{//一次性节点编辑
            if(nodeName!=''){
                if(dateNum==''){
                    $$.modal.alert('相对日期时"距离上一个节点"不能为空','确定')
                }else{
                    for(var i=0;i<len;i++){
                        if(i!=editIndex){
                            if(nodeName==boxNode.eq(i).find('.name').text()){
                                isRepeat=true;
                                console.log(i,editIndex)
                            }
                        }
                    }
                    if(isRepeat==true){//判断节点名称重复
                        $$.modal.alert('节点名称重复，请修改','确定');
                        isRepeat=false;
                    }else{
                        var dataInit=JSON.parse(decodeURI($('.node-item-box').eq(editIndex).attr('data-message')));
                        var nodeParameter=function(){
                            saveItem.step=dataInit.step;
                            saveItem.id=dataInit.id;
                            saveItem.forms=dataInit.forms;
                            saveItem.copystepid=dataInit.copystepid;
                            var saveItemString=JSON.stringify(saveItem);
                            boxNode.eq(editIndex).attr('data-message',encodeURI(saveItemString));
                            boxNode.eq(editIndex).find('.name').text(nodeName);
                            boxNode.eq(editIndex).find('.gray').text(nodeDes);
                            boxNode.eq(editIndex).find('.time').text(''+fuhao+' '+dateNum+' '+dateNumType);
                            $('#editPointtwo').modal('hide');
                            singleClear();
                            isEdit=false;
                        };
                        //判断参考节点是否变化
                        if(singleReference!=dataInit.basestep){
                            if(singleReference=='开始随访'){
                                nodeParameter();
                                $('.begin-node').append(boxNode.eq(editIndex));
                                nodeInit();
                            }else{
                                for(var i=0;i<len;i++){//判断便后后的节点是否有子节点
                                    var boxData=JSON.parse(decodeURI(boxNode.eq(i).attr('data-message')));
                                    if(boxData.basestep==singleReference){
                                        changeNode=true;
                                        break;
                                    }
                                }
                                if(changeNode==true){//变化参考节点存在子节点时
                                    var singleArry=[];//创建一个空数组来存子节点
                                    for(var i=0;i<len;i++){
                                        var boxChange=JSON.parse(decodeURI(boxNode.eq(i).attr('data-message')));
                                        if(boxChange.basestep==singleReference){
                                            singleArry.push(boxNode.eq(i))
                                        }
                                    }
                                    nodeParameter();
                                    boxNode.eq(editIndex).insertAfter(singleArry[singleArry.length-1]);
                                    nodeInit();
                                }else{//变化参考节点不存在子节点时
                                    nodeParameter();
                                    for(var i=0;i<len;i++){
                                        var boxData=JSON.parse(decodeURI(boxNode.eq(i).attr('data-message')));
                                        if(boxData.title==singleReference){
                                            boxNode.eq(editIndex).insertAfter(boxNode.eq(i));
                                            nodeInit();
                                        }
                                    }
                                }
                            }
                        }else{
                            nodeParameter();
                        }
                    }
                }
            }else{
                $$.modal.alert('请输入节点名称','确定')
            }
        }
    });
    //保存重复节点
    $('#saveRepeatNodeBtn').click(function () {
        var $currentParent = $('#editPointthr');
        var nodeName= $.trim($currentParent.find('.node-name').val());//定义名称title
        var repeatMode=$currentParent.find('.repeat-mode').val();//月周日重复
        var datePeriodtype='';
        if(repeatMode=='每月重复'){
            datePeriodtype=5
        }else if(repeatMode=='每周重复'){
            datePeriodtype=4
        }else if(repeatMode=='每日重复'){
            datePeriodtype=3
        }
        var continuedSum=parseInt($.trim($currentParent.find('.continued-num').val()));//定义持续的事件
        var continuedType='';//定义持续时间的类型
        if($currentParent.find('.continued-num-type').val()=='月'){
            continuedType=5
        }else if($currentParent.find('.continued-num-type').val()=='周'){
            continuedType=4
        }else if($currentParent.find('.continued-num-type').val()=='日'){
            continuedType=3
        }
        var nodeDes=$.trim($currentParent.find('.node-des').val());//找到描述的节点
        if(nodeDes==''){
            nodeDes='单击填写描述'
        }
        var nodeJurisdiction=$currentParent.find('.node-jurisdiction').val();//找到权限节点
        var jurisdictionLimit='';
        if(nodeJurisdiction=='v1'){
            jurisdictionLimit=3
        }else{
            jurisdictionLimit=1
        }
        var commentEnable='';//定义节点评论
        if($currentParent.find('.node-review').prop('checked')){
            commentEnable=1;
        }else{
            commentEnable=0;
        }
        //定义提前提醒
        var beforeValue= $.trim($currentParent.find('.before-value').val());
        var beforeNotify='';
        if($currentParent.find('.before-doc').prop('checked')&&$currentParent.find('.before-patient').prop('checked')){
            beforeNotify=3
        }else if($currentParent.find('.before-doc').prop('checked')){
            beforeNotify=1
        }else if($currentParent.find('.before-patient').prop('checked')){
            beforeNotify=2
        }
        //定义到时提醒
        var notifyNew='';
        if($currentParent.find('.notify-doc').prop('checked')&&$currentParent.find('.notify-patient').prop('checked')){
            notifyNew=3
        }else if($currentParent.find('.notify-doc').prop('checked')){
            notifyNew=1
        }else if($currentParent.find('.notify-patient').prop('checked')){
            notifyNew=2
        }
        //定义预期提醒
        var overValue= $.trim($currentParent.find('.over-value').val());
        var overNotify='';
        if($currentParent.find('.over-doc').prop('checked')&&$currentParent.find('.over-patient').prop('checked')){
            overNotify=3
        }else if($currentParent.find('.over-doc').prop('checked')){
            overNotify=1
        }else if($currentParent.find('.over-patient').prop('checked')){
            overNotify=2
        }
        //定义通知方式
        var msgType='';
        if($currentParent.find('.msg-system').prop('checked')&&$currentParent.find('.msg-message').prop('checked')){
            msgType=3
        }else if($currentParent.find('.msg-system').prop('checked')){
            msgType=1
        }else if($currentParent.find('.msg-message').prop('checked')){
            msgType=2
        }
        var stepIndex='';
        //if($('.form-node').html()==''){
        //    stepIndex=0;
        //}else{
        //    stepIndex=JSON.parse(decodeURI($('.form-node .node-item-box:last-child').attr('data-message'))).step+1;
        //}
        var repeatReference=$currentParent.find('.selectReference').val();//定义参考节点
        saveItem={
            periodtype:datePeriodtype,
            period:1,
            isInfinite:1,
            templateid:urlParamObj.templateid,
            title:nodeName,
            beforenotify:{ type:3,time:beforeValue,direct:beforeNotify},
            notify:{direct:notifyNew},
            overduenotify:{type:3,time:overValue,direct:overNotify},
            filltype:jurisdictionLimit,
            description:nodeDes,
            step:stepIndex,
            forms:[],
            msgtype:msgType,
            labled:commentEnable,
            goingtime: continuedSum,
            goingtype:continuedType,
            basestep:repeatReference
        };
        var boxNode=$('.node-item-box');//找到所有的节点
        var isNode=false;//定义是否有字节点
        var changeNode=false;//定义改变后参考节点是否有子节点
        var isRepeat=false;//定义是否重复名字
        var len=boxNode.length;
        if(isEdit==false){
            if(nodeName!=''){
                for(var i=0;i<len;i++){
                    if(nodeName==boxNode.eq(i).find('.name').text()){
                        isRepeat=true;
                    }
                }
                if(isRepeat==true){//判断名称是否重复
                    $$.modal.alert('节点名称重复，请修改','确定');
                    isRepeat=false;
                }else{
                    isNode=false;
                    var repeatNode=new pageRendering(nodeName,'',repeatMode,'',nodeDes,saveItem.forms);
                    var html=repeatNode.html;
                    var saveItemStr=JSON.stringify(saveItem);
                    html.setAttribute('data-message',encodeURI(saveItemStr));
                    if(repeatReference=='开始随访'){
                        $('.begin-node').append(html)
                    }else{
                        for(var i= 0;i<len;i++){
                            var boxNodeJson=JSON.parse(decodeURI(boxNode.eq(i).attr('data-message')));
                            if(boxNodeJson.basestep==repeatReference){
                                isNode=true;
                                break;
                            }
                        }
                        if(isNode==false){//判断是否有子节点操作
                            for(var i= 0;i<len;i++){
                                var boxNodeData=JSON.parse(decodeURI(boxNode.eq(i).attr('data-message')));
                                if(boxNodeData.title==repeatReference){
                                    boxNode.eq(i).after(html);
                                }
                            }
                        }else{
                            var nodeArry=[];
                            for(var i= 0;i<len;i++){
                                var boxNodeData=JSON.parse(decodeURI(boxNode.eq(i).attr('data-message')));
                                if (boxNodeData.basestep==repeatReference){
                                    nodeArry.push(boxNode.eq(i))
                                }
                            }
                            nodeArry[nodeArry.length-1].after(html);
                        }
                    }
                    $('#editPointthr').modal('hide');
                    nodeInit();
                    repeatClear();
                }//判断名称重复
            }else{
                $$.modal.alert('节点名称不能为空','确定');
            }
        }else{//重复性节点编辑
            if(nodeName!=''){
                for(var i= 0,len=boxNode.length;i<len;i++){
                    if(i!=editIndex){
                        if(nodeName==boxNode.eq(i).find('.name').text()){
                            isRepeat=true;
                        }
                    }
                }
                if(isRepeat==true){
                    $$.modal.alert('节点名称重复，请修改','确定');
                    isRepeat=false;
                }else{
                    var dataInit=JSON.parse(decodeURI($('.node-item-box').eq(editIndex).attr('data-message')));
                    var nodeParameter=function(){
                        saveItem.step=dataInit.step;
                        saveItem.id=dataInit.id;
                        saveItem.forms=dataInit.forms;
                        saveItem.copystepid=dataInit.copystepid;
                        var saveItemString=JSON.stringify(saveItem);
                        boxNode.eq(editIndex).attr('data-message',encodeURI(saveItemString));
                        boxNode.eq(editIndex).find('.name').text(nodeName);
                        boxNode.eq(editIndex).find('.gray').text(nodeDes);
                        boxNode.eq(editIndex).find('.time').text(' '+repeatMode);
                        $('#editPointthr').modal('hide');
                        repeatClear();
                        isEdit=false;
                    };
                    //判断参考节点是否变化
                    if(repeatReference!=dataInit.basestep){
                        if(repeatReference=='开始随访'){
                            nodeParameter();
                            $('.begin-node').append(boxNode.eq(editIndex));
                            nodeInit();
                        }else{
                            for(var i=0;i<len;i++){//判断便后后的节点是否有子节点
                                var boxData=JSON.parse(decodeURI(boxNode.eq(i).attr('data-message')));
                                if(boxData.basestep==repeatReference){
                                    changeNode=true;
                                    break;
                                }
                            }
                            if(changeNode==true){//判断是否有子节点===
                                var singleArry=[];//创建一个空数组来存子节点
                                for(var i=0;i<len;i++){
                                    var boxChange=JSON.parse(decodeURI(boxNode.eq(i).attr('data-message')));
                                    if(boxChange.basestep==repeatReference){
                                        singleArry.push(boxNode.eq(i))
                                    }
                                }
                                nodeParameter();
                                boxNode.eq(editIndex).insertAfter(singleArry[singleArry.length-1]);
                                nodeInit();
                            }else{
                                nodeParameter();
                                for(var i=0;i<len;i++){
                                    var boxData=JSON.parse(decodeURI(boxNode.eq(i).attr('data-message')));
                                    if(boxData.title==repeatReference){
                                        boxNode.eq(editIndex).insertAfter(boxNode.eq(i));
                                        nodeInit();
                                    }
                                }
                            }
                        }
                    }else{
                        nodeParameter();
                    }
                }
            }else{
             $$.modal.alert('节点名称不能为空','确定')
            }
        }
    });
    //时间参考节点保存
    $('#timeNodeBtn').click(function(){
        var $thisparent=$('#timeNode');
        var nodeName= $.trim($thisparent.find('.node-name').val());//节点名称
        var nodeDes= $.trim($thisparent.find('.node-des').val());//描述
        if(nodeDes==''){
            nodeDes='单击填写描述'
        }
        var checkLimit = $thisparent.find('.node-jurisdiction').val();//定义权限===
        var jurisdictionLimit='';//定义权限
        if(checkLimit=='v1'){
            jurisdictionLimit=3;
        }else if(checkLimit=='v2'){
            jurisdictionLimit=1;
        }
        var commentEnable='';//定义节点评论的开启
        if($thisparent.find('.comment-enable').prop('checked')){
            commentEnable=1
        }else{
            commentEnable=0;
        }
        var beforeValue= $.trim($thisparent.find('.before-value').val());//提前天数
        var beforeNotify='';//定义提前提醒
        if($thisparent.find('.before-doc').prop('checked')&&$thisparent.find('.before-patient').prop('checked')){
            beforeNotify=3;
        }else if($thisparent.find('.before-doc').prop('checked')){
            beforeNotify=1;
        }else if($thisparent.find('.before-patient').prop('checked')){
            beforeNotify=2;
        }
        var notifyNew='';//定义到时提醒
        if($thisparent.find('.notify-doc').prop('checked')&&$thisparent.find('.notify-patient').prop('checked')){
            notifyNew=3;
        }else if($thisparent.find('.notify-doc').prop('checked')){
            notifyNew=1;
        }else if($thisparent.find('.notify-patient').prop('checked')){
            notifyNew=2;
        }
        var overNotify='';//定义预期提醒
        var overVlue= $.trim($thisparent.find('.over-value').val());
        if($thisparent.find('.over-doc').prop('checked')&&$thisparent.find('.over-patient').prop('checked')){
            overNotify=3;
        }else if($thisparent.find('.over-doc').prop('checked')){
            overNotify=1;
        }else if($thisparent.find('.over-patient').prop('checked')){
            overNotify=2;
        }
        var msgType='';//系统或者短信提醒
        if($thisparent.find('.msg-system').prop('checked')&&$thisparent.find('.msg-message').prop('checked')){
            msgType=3;
        }else if($thisparent.find('.msg-system').prop('checked')){
            msgType=1;
        }else if($thisparent.find('.msg-message').prop('checked')){
            msgType=2;
        }
        var stepIndex='';//定义步骤数
        if($('.form-node').html()==''){
            stepIndex=0;
        }else{
            stepIndex=JSON.parse(decodeURI($('.form-node .node-item-box:last-child').attr('data-message'))).step+1;
        }
        saveItem={//参数
            periodtype:0,
            isInfinite:0,
            templateid:urlParamObj.templateid,
            title:nodeName,
            beforenotify:{ type:3,time:beforeValue,direct:beforeNotify},
            notify:{direct:notifyNew},
            overduenotify:{type:3,time:overVlue,direct:overNotify},
            filltype:jurisdictionLimit,
            description:nodeDes,
            step:stepIndex,
            forms:[],
            msgtype:msgType,
            labled:commentEnable
        };
        var boxNode=$('.node-item-box');//找到所有节点
        var isRepeat=false;//定义名称是否重复
        var len=boxNode.length;
        if(isEdit==false){//说明为新建不是编辑节点
            if(nodeName!=''){
                for(var i=0;i<len;i++){
                    if(nodeName==boxNode.eq(i).find('.name').text()){
                        isRepeat=true;
                    }
                }
                if(isRepeat==true){
                    $$.modal.alert('节点名称重复，请修改','确定');
                    isRepeat=false;
                }else{
                    var timeNode=new pageRendering(nodeName,'','时间参考节点','',nodeDes,saveItem.forms);
                    var html=timeNode.html;
                    $('.form-node').append(html);
                    var saveItemStr=JSON.stringify(saveItem);
                    html.setAttribute('data-message',encodeURI(saveItemStr));
                    $('#timeNode').modal('hide');
                    nodeInit();
                    singleClear();
                }
            }else{
                $$.modal.alert('节点名称不能为空','确定')
            }
        }else{
            if(nodeName!=''){
                for(var i=0;i<len;i++){
                    if(i!=editIndex){
                        if(nodeName==boxNode.eq(i).find('.name').text()){
                            isRepeat=true;
                        }
                    }
                }
                if(isRepeat==true){
                    $$.modal.alert('节点名称重复，请修改','确定');
                    isRepeat=false;
                }else{
                    var dataInit=JSON.parse(decodeURI(boxNode.eq(editIndex).attr('data-message')));
                    saveItem.step=dataInit.step;
                    saveItem.id=dataInit.id;
                    saveItem.forms=dataInit.forms;
                    saveItem.copystepid=dataInit.copystepid;
                    var saveItemString=JSON.stringify(saveItem);
                    boxNode.eq(editIndex).attr('data-message',encodeURI(saveItemString));
                    boxNode.eq(editIndex).find('.name').text(nodeName);
                    boxNode.eq(editIndex).find('.gray').text(nodeDes);
                    boxNode.eq(editIndex).find('.time').text(' '+'时间参考节点');
                    $('#timeNode').modal('hide');
                    //当绝对节点的名称发生变化时，子节点相关basestep也要变化
                    if(nodeName!=dataInit.title){
                        for(var i=0;i<len;i++){
                            var nodeStep=JSON.parse(decodeURI(boxNode.eq(i).attr('data-message')));
                            if(nodeStep.basestep==dataInit.title){
                               nodeStep.basestep=nodeName;
                                var newDataMessage=encodeURI(JSON.stringify(nodeStep));
                                boxNode.eq(i).attr('data-message',newDataMessage);
                            }
                        }
                    }
                    timeClear();
                    isEdit=false;
                }
            }else{
                $$.modal.alert('节点名称不能为空','确定');
            }
        }
    })
};
//页面渲染封装
var pageRendering=function(nodeName,fuhao,dateNum,dateNumType,descripe,forms){
    var html=document.createElement('div');
    this.html=html;
    html.setAttribute('class','node-item-box');
    html.innerHTML="<i class='left-index material-icons'>&#xE873;</i>"+
    "<div class='content-box'>"+
    "<div class='head'>"+
    "<p class='name'>"+nodeName+"</p>"+
    "<span class='time'>"+''+fuhao+' '+dateNum+' '+dateNumType+"</span>"+
    "</div>"+
    "<div class='node-list'>"+
    "<ul>"+
    "<li class='gray'>"+descripe+"</li>"+
    "<li class='blue add-more'><a href='javascript:;'><i class='material-icons'>&#xE145;</i><span>更多</span></a></li>"+
    "</ul>"+
    "<div class='operate-group'>"+
    "<a href='javascript:;' class='edit-btn'><i class='material-icons'>&#xE3C9;</i></a>"+
    "<a href='javascript:;' class='del-btn'><i class='delete-icon'></i></a>"+
    "</div> </div> </div>";
    var len=forms.length;
    if(len!=0){
        for(var i=0;i<len;i++){
            var insertLi=document.createElement('li');
            insertLi.setAttribute('class','blue node-form-item');
            insertLi.setAttribute('data-form-id',forms[i].id);
            insertLi.innerHTML="<span class='del-form'>&times;</span>"+
            "<a href='javascript:;'>"+(i+1)+'、'+forms[i].title+"</a>";
            var $html=$(html);
            $html.find('.add-more').before(insertLi);
        }
    }
};
//页面初始化刷新读取
var pageFresh=function(){
    new followupPlan().getTempNodeList(urlParamObj.templateid,function(res,status){
        res = JSON.parse(res);
        if(res.code== '000'){
            var resData=JSON.parse(res.data);
            if(resData.length!=0){
                for(var i= 0,len=resData.length;i<len;i++){
                    var periodType='';
                    var nodeName=resData[i].title,
                        fuhao='+',
                        dateNum=resData[i].period,
                        descripe= $.trim(resData[i].description);
                    if(!descripe){
                        descripe='单击填写描述'
                    }
                    if(resData[i].isInfinite==0){
                        if(resData[i].periodtype==3){
                            periodType='日'
                        }else if(resData[i].periodtype==4){
                            periodType='周'
                        }else if(resData[i].periodtype==5){
                            periodType='月'
                        }else if(resData[i].periodtype==0){
                            fuhao='';
                            dateNum='时间参考节点';
                            periodType='';
                        }
                    }else{
                        fuhao='';
                        if(resData[i].periodtype==3){
                            dateNum='每日重复'
                        }else if(resData[i].periodtype==4){
                            dateNum='每周重复'
                        }else if(resData[i].periodtype==5){
                            dateNum='每月重复'
                        }
                    }
                    var forms=resData[i].forms;
                    var pageLoad=new pageRendering(nodeName,fuhao,dateNum,periodType,descripe,forms);
                    var html=pageLoad.html;
                    html.setAttribute('data-message',encodeURI(JSON.stringify(resData[i])));
                    if(resData[i].basestep=='开始随访' || (!resData[i].basestep && resData[i].periodtype!=0)){
                        $('.begin-node').append(html)
                    }else{
                        $('.form-node').append(html);
                    }
                }
                $('.empty-tips').addClass('hidden');
                $(  '.form-node').removeClass('hidden');
                nodeInit();
            }
        }
        $('.outer').addClass('active');
    });
};
//前面序号初始化==
var nodeInit=function(){
    if($('.form-node').html()!=''){
        var $thisParent=$('.node-item-box');
        var $thisNode=$('.node-item-box>i');
        var len=$thisNode.length;
        var nodeNum=1;
        for(var i= 0;i<len;i++){
            var nodePeriodType=JSON.parse(decodeURI($thisParent.eq(i).attr('data-message'))).periodtype;
            if(nodePeriodType==0){
                nodeNum=0;
            }
            if(nodeNum==0){
                $thisNode.eq(i).replaceWith("<i class='left-index material-icons'>&#xE873;</i>");
            }else{
                $thisNode.eq(i).removeClass('material-icons').text(nodeNum);
            }
            nodeNum++;
        }
        //消除最后一个box的左侧边线。。。。
        if($('.form-node').children().length==1){
            $('#beginNode .node-item-box:nth-last-of-type(1)').addClass('box-especially').siblings().removeClass('box-especially')
        }else{
            $('#beginNode .node-item-box').removeClass('box-especially')
        }
        $('.empty-tips').addClass('hidden');
        $('.form-node').removeClass('hidden');
    }
};
//保存页面节点列表================================
var saveNode=function(){
    $('#submitForm').click(function(){
       saveNodeAjax(function (res) {
           $$.modal.tips('保存成功',1000);
           setTimeout(function () {
               location.reload();
           },1000);
       })
    })
};
//保存节点ajax
var saveArry=[];
var saveNodeAjax = function (cb) {
    saveArry.length=0;
    for(var i= 0,len=$('.node-item-box').length;i<len;i++){
        var textJson=decodeURI($('.node-item-box').eq(i).attr('data-message'));
        var saveItemJson = JSON.parse(textJson);
        saveItemJson.step = i;
        saveArry.push(saveItemJson);
    }
    new followupPlan().setTempNodeList(saveArry,urlParamObj.templateid,function(res,status){
        var res = JSON.parse(res);
        if(res.code == '000'){
            cb(res);
        }else{
            $$.modal.tips('保存失败',2000);
        }
    });
};
//更多节点添加========
var addMore=function(){
    $('.form-node').on('click','.add-more',function(){
        var $thisParent = $(this).parents('.node-item-box');
        var dataIndex = $('.node-item-box').index($thisParent);
        saveNodeAjax(function(res){
            var stepId=JSON.parse(res.data)[dataIndex];
            var templateId = urlParamObj.templateid;
            if(res.code== '000'){
                location.href='./edit-form.html?templateid='+templateId+'&stepid='+stepId;
            }
        });
    });
};
//具体节点点击=======
var specificNode=function(){
    $('.form-node').on('click','.node-form-item',function(){
        var $thisParent = $(this).parents('.node-item-box');
        var formId = $(this).attr('data-form-id');
        var dataIndex = $('.node-item-box').index($thisParent);
        saveNodeAjax(function(res){
            if(res.code== '000'){
                var templateId = urlParamObj.templateid;
                var stepId = JSON.parse(res.data)[dataIndex];
                location.href='./edit-form.html?templateid='+templateId+'&stepid='+stepId+'&formid='+formId;
            }
        });
    })
};

//一次性节点清空===
var singleClear=function(){
    var $single=$('#editPointtwo');
    $('#editPointtwo input').val('').removeProp('checked');
    $('#editPointtwo textarea').val('');
    $single.find('.date-num-type').val('月');
    $single.find('.check-limit').val('v1');
};
//重复性节点清空
var repeatClear=function(){
    var $repeat=$('#editPointthr');
    $('#editPointthr input').val('').removeProp('checked');
    $('#editPointthr textarea').val('');
    $repeat.find('.repeat-mode').val('每月重复');
    $repeat.find('node-jurisdiction').val('v1');
    $repeat.find('.continued-num-type').val('月');
};
//时间节点清空
var timeClear=function(){
    var $time=$('#timeNode');
    $('#timeNode input').val('').removeProp('checked');
    $('#timeNode textarea').val('');
    $time.find('.node-jurisdiction').val('v1');

};
//离开页面提示
var leavePageAlert = function () {
    //关闭页面、刷新页面
    var tempFunction =  function(event) {event.returnValue = '';};
    window.addEventListener("beforeunload",tempFunction);
    //监听a标签
    $('body').on('click','a',function (e) {
        if($(this).attr('id') == 'submitForm'){
            window.removeEventListener("beforeunload",tempFunction);
            return false;
        }
        var href = $(this).attr('href');
        if((href.indexOf('#') != 0) && (href != 'javascript:;') && (href != 'javascript:void(0);') && (href != 'javascript:void(0)')){
            e.preventDefault();
            $$.modal.confirm('你即将离开页面，请确保数据已保存','取消','确定',function () {
                window.removeEventListener("beforeunload",tempFunction);
                location.href = href;
            });
        }else{
            window.removeEventListener("beforeunload",tempFunction);
            setTimeout(function () {
                window.addEventListener("beforeunload",tempFunction);
            },500);
        }
    })
};
//参考节点读取
var referenceNode=function(){
    $('.selectReference').html('');
    var $allBox=$('.node-item-box');
    var nameArry=['开始随访'];//定义一个空数组来装绝对节点的名称
    for(var i= 0,len=$allBox.length;i<len;i++){
        var nodeData=JSON.parse(decodeURI($allBox.eq(i).attr('data-message')));
        if(nodeData.periodtype==0){
            nameArry.push(nodeData.title)
        }
    }
    for(var i=0;i<nameArry.length;i++){
        var html=document.createElement('option');
        html.value=nameArry[i];
        html.innerText=nameArry[i];
        $('.selectReference').append(html)
    }
};
//给复制时一个随机验证码
var copyRandom=function(){
    var code='';
    var selectChar=new Array(2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z');
    for(var i=0;i<4;i++){
        var charIndex = Math.floor(Math.random()*32);
        code+=selectChar[charIndex]
    }
    return code;
};
$(function () {
    if(urlParamObj.templateid){
        $('#returnBase').attr('href','./edit-base.html?templateid='+urlParamObj.templateid);
    }
    calcFormHeight();
    $(window).resize(function () {
        calcFormHeight();
    });
    nodeModalOperate();
    nodeOperate();
    pageFresh();
    saveNode();
    addMore();
    specificNode();
    leavePageAlert();
});

